package com.cxs.videoplayer.component;

import com.cxs.videoplayer.ResourceTable;
import com.cxs.videoplayer.data.DeviceInfo;
import com.cxs.videoplayer.provider.DeviceListProvider;
import com.cxs.videoplayer.util.DeviceUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class DeviceListView extends DirectionalLayout{

    private Context context;
    DirectionalLayout layout;
    AbilitySlice slice;

    public DeviceListView(Context context, AbilitySlice slice) {
        super(context);
        this.context = context;
        this.slice = slice;
    }

    public DirectionalLayout getView() {
        layout = (DirectionalLayout) LayoutScatter.getInstance(context)
                .parse(ResourceTable.Layout_device_list, null, false);
        ListContainer listContainer = (ListContainer) layout.findComponentById(ResourceTable.Id_device_listcontainer);

        DeviceListProvider deviceList = new DeviceListProvider(getData());
        deviceList.setDeviceClickedListener(deviceId -> {
            System.out.println("deviceId: " + deviceId);
            startFA(deviceId);
        });
        listContainer.setItemProvider(deviceList);

        return layout;
    }

    private List<DeviceInfo> getData() {
        List<DeviceInfo> deviceInfos = new ArrayList<>();

        // 本地设备
        deviceInfos.add(new DeviceInfo("", DeviceUtils.getLocalDeviceName(context) + "(本机)"));

        Map<String, String> deviceList = DeviceUtils.getDeviceList();
        if (deviceList != null && deviceList.size() > 0) {
            Set<Map.Entry<String, String>> entries = deviceList.entrySet();
            // 远程设备
            for (Map.Entry<String, String> entry : entries) {
                deviceInfos.add(new DeviceInfo(entry.getKey(), entry.getValue()));
            }
        }

        return deviceInfos;
    }

    private void startFA(String deviceId) {
        if (!deviceId.equals("")) {
            slice.continueAbility(deviceId);
        }
    }
}
